package com.navi.mould1.controller;
import com.navi.bean.table.Bis_user;
import com.navi.core.util.JdbcUtils;
import com.navi.core.util.LoggerUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.util.List;


@Controller
public class LinkController {
    QueryRunner qr = new QueryRunner();

//    // 例: http://10.0.3.65/jn-report/link-jn-report?userId=123&userName=123&fabId=123
//    @RequestMapping(value = "/link-jn-report")
//    public void linkReport_1(String userId, String userName, String fabId, HttpServletRequest request, HttpServletResponse response) {
//        HttpSession session = request.getSession();
//        session.setAttribute("hasTryFlg", "Y");
//        session.setAttribute("userId", userId);
//        session.setAttribute("userName", userName);
//        session.setAttribute("fabId", fabId);
//        try {
//            response.sendRedirect("/jn-report/login");
//        }catch (IOException e){
//            e.printStackTrace();
//        }
//    }


    // 例: http://10.0.3.65/jn-report/link-jn-report?userId=admin&password=Ab123456
    @RequestMapping(value = "/link-jn-report")
    public void linkReport_2(String userId, String password, HttpServletRequest request, HttpServletResponse response) {
        if (userId != null && password != null){
            try (Connection conn = JdbcUtils.getMySQLConnection()){
                List<Bis_user> bis_user_list = qr.query(conn, "select * from icim_jn.bis_user where usr_id='" + userId + "' and usr_key='" + password + "'", new BeanListHandler<>(Bis_user.class));
                if (CollectionUtils.isNotEmpty(bis_user_list)) {
                    Bis_user user = bis_user_list.get(0);
                    HttpSession session = request.getSession();
                    session.setAttribute("hasTryFlg", "Y");
                    session.setAttribute("userId", user.getUsr_id());
                    session.setAttribute("userName", user.getUsr_name());
                    session.setAttribute("fabId", user.getFab_id());
                    session.setMaxInactiveInterval(10*60*60);
                }
            } catch (Exception e) {
                LoggerFactory.getLogger(this.getClass()).error(LoggerUtil.stackTraceToString(e));
                e.printStackTrace();
            }
        }
        try {
            response.sendRedirect("/jn-report/login");
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}